package com.tianchi.lexiang.util;

import java.io.IOException;
import java.net.UnknownHostException;

import com.tianchi.lexiang.constant.Commands;
import com.tianchi.lexiang.socketclient.SocketConnectUtil;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

public class DatabaseVersionUtil {
	private static final String TAG = "DatabaseVersionUtil";
	private static final String DB_VERSION_XML = "tianchi_db_version";
	private static final String VERSION = "version";
	private static final String DEFAULT_VERSION = "0-0";
	
	private static String serverDBVersion;
	
	public static void recordServerDBVersion(String version){
		Log.d(TAG, "[recordServerDBVersion] version ==> " + version);
		serverDBVersion = version.trim();
	}
	
	public static String getRecordServerDBVersion(){
		Log.d(TAG, "[getRecordServerDBVersion] getServerVersion ==> " + serverDBVersion);
		return serverDBVersion.trim();
	}
	
	public static String getDBVersion(Context mContext){
		SharedPreferences prefs = mContext.getSharedPreferences(DB_VERSION_XML, Context.MODE_PRIVATE);
		String version = prefs.getString(VERSION, DEFAULT_VERSION);
		Log.d(TAG, "[getDBVersion] version=>"+version);
		return version.trim();
	}
	
	public static void persistDBVersion(Context mContext,String version){
		SharedPreferences prefs = mContext.getSharedPreferences(DB_VERSION_XML, Context.MODE_PRIVATE);
		prefs.edit().putString(VERSION,version.trim()).commit();
		Log.d(TAG, "[persistDBVersion] version=>"+version);
	}
	
	public static void sendVersionToServer(Context mContext){
		SocketConnectUtil mSocket;
		try {
			mSocket = SocketConnectUtil.getSocketConnectUtil();
			Commands cmdObj = new Commands(Commands.CMD_QUERY_VERSION, getDBVersion(mContext));
			if (mSocket != null && !mSocket.isClosed()) {
				String detailCmd = cmdObj.translateToDetailCmd();
				Log.d(TAG, "detailCmd =>"+detailCmd);
				mSocket.sendSocket(detailCmd);
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
